import { defineStore } from "pinia";
import { ref } from "vue";

export const useCartStore = defineStore("cart", () => {
  const cartItems = ref([]);

  const loadCart = () => {
    const cart = localStorage.getItem("pinia-cart");
    if (cart) {
      cartItems.value = JSON.parse(cart);
    }
  };

  const saveCart = () => {
    localStorage.setItem("pinia-cart", JSON.stringify(cartItems.value));
  };

  const addToCart = (product) => {
    cartItems.value.push(product);
    saveCart();
  };

  const removeFromCart = (product) => {
    cartItems.value = cartItems.value.filter((item) => item.id !== product);
    saveCart();
  };

  const clearCart = () => { 
    cartItems.value = [];
    localStorage.removeItem("pinia-cart");
  };

  const cartTotal = (() => {
    return cartItems.value.reduce((total, item) => total + item.price, 0);
  });

  loadCart();

  return { cartItems, addToCart, removeFromCart, clearCart, loadCart,cartTotal };
},{
  persist: true
});